﻿namespace Jsl.StyleCop.CSharp
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using Microsoft.StyleCop;
    using Microsoft.StyleCop.CSharp;

    [SourceAnalyzer(typeof(CsParser))]
    public class MethodCollectorRule : SourceAnalyzer
    {
        /// <summary>
        /// Rule name used by testing.
        /// </summary>
        public static readonly string MethodRule = "MethodRule";

        private static List<Method> methods;
        private static bool enableRule;

        #region Constructors
        public MethodCollectorRule()
        {
        }
        #endregion Constructors

        #region Public Properties
        public static bool EnableRule
        {
            get { return MethodCollectorRule.enableRule; }
            set { MethodCollectorRule.enableRule = value; }
        }

        public static List<Method> Methods
        {
            get { return MethodCollectorRule.methods; }
        }
        #endregion Public Properties

        #region Public Methods
        public override void AnalyzeDocument(CodeDocument document)
        {
            if (!MethodCollectorRule.EnableRule)
            {
                return;
            }

            MethodCollectorRule.methods = new List<Method>();

            CsDocument csharpDocument = (CsDocument)document;
            csharpDocument.WalkDocument(this.CollectMethods);
        }

        public override bool IsRuleEnabled(CodeDocument document, string ruleName)
        {
            return MethodCollectorRule.enableRule;
        }
        #endregion Public Methods

        #region Private Methods
        private bool CollectMethods(CsElement element, CsElement parentElement, object context)
        {
            Method method = element as Method;
            if (method != null)
            {
                MethodCollectorRule.methods.Add(method);
            }

            return true;
        }
        #endregion Private Methods
    }
}